var xhr = new Array(); // ARRAY OF XML-HTTP REQUESTS
var ids = new Array(); // ARRAY OF XML-HTTP REQUESTS
var xi = new Array(0); // ARRAY OF XML-HTTP REQUEST INDEXES
var nowAvailable = 0;  // UPDATED ON FREEING AN XML-HTTP REQUEST
xi[0] = 1; // FIRST INDEX SET TO 1 MAKING IT AVAILABLE

function xhrRequest(type) {
	if (!type) {
		type = 'html';
	}


	// xhrsend IS THE xi POSITION THAT GETS PASSED BACK
	// INITIALIZED TO THE LENGTH OF THE ARRAY(LAST POSITION + 1)
	// IN CASE A FREE RESOURCE ISN'T FOUND IN THE LOOP
	var xhrsend = xi.length;

	// IF SOME REQUEST IS RECENTLY FREED USE IT
	if(nowAvailable!=-1)
	{
		xhrsend = nowAvailable;
		xi[nowAvailable] = 0;
		nowAvailable = -1;
	}
	else
	{
		// GO THROUGH AVAILABLE xi VALUES
		for (var i=0; i<xi.length; i++) {

			// IF IT'S 1 (AVAILABLE), ALLOCATE IT FOR USE AND BREAK
			if (xi[i] == 1) {
				xi[i] = 0;
				xhrsend = i;
				break;
			}
		}
	}

	// SET TO 0 SINCE IT'S NOW ALLOCATED FOR USE
	xi[xhrsend] = 0;

	// SET UP THE REQUEST
	if (window.ActiveXObject) {
		try {
			xhr[xhrsend] = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhr[xhrsend] = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	} else if (window.XMLHttpRequest) {
		xhr[xhrsend] = new XMLHttpRequest();
		if (xhr[xhrsend].overrideMimeType) {
			xhr[xhrsend].overrideMimeType('text/' + type);
		}
	}
	return (xhrsend);
};


function ajaxRequest(url, text, id) {

	var xhri = xhrRequest('xml');
	ids[xhri] = id;
	xhr[xhri].onreadystatechange = function() {
		if (xhr[xhri].readyState == 4 || xhr[xhri].readyState == "complete") {
//			document.getElementById('debug').innerHTML = xhr[xhri].responseText;
			xmlDoc=xhr[xhri].responseXML;
			xmlDoc.preserveWhiteSpace = true;
			root = xmlDoc.documentElement;
			updateResponse(root, ids[xhri]);

			//FREE THE OBJECT AND THEN UPDATE FLAG
			xhr[xhri] = null;
			xi[xhri] = 1;
			if(nowAvailable==-1)
				nowAvailable = xhri;
		}
	};
	xhr[xhri].open("POST", url, true);
	xhr[xhri].setRequestHeader("Man", "GET search.php HTTP/1.1");
        xhr[xhri].setRequestHeader("MessageType", "CALL");
        xhr[xhri].setRequestHeader("Content-Type", "text/xml; charset=utf-8");

	xhr[xhri].send(text);
};
